%Beta GMM estimation
function [beta] = BetaGMM(pStock, pIndex,lu,ld)

rStock = getReturn(pStock);
rIndex = getReturn(pIndex);

%Create the set of non-limit observations
T = length(rStock);
t = 1;
for i =1:T
    if rStock(i) > ld && rStock(i) < lu
        S(t) = i;
        t = t+1;
    end
end
N = length(S);

%Calculate var of rIndex, cov(rStock, rIndex) , beta
sigma2 = 0;
cov = 0;
for j=2:N
    %rStock, rIndex co lay log ko
    temp = log(pIndex(S(j))/pIndex(S(j-1)))-(S(j)-S(j-1))*mean(log(rIndex+1));
    sigma2 = sigma2 + temp^2;
    cov = cov + temp*(log(pStock(S(j))/pStock(S(j-1)))-(S(j)-S(j-1))*mean(log(rStock+1)));
end
cov = cov/T;
sigma2 = sigma2/T;
beta = cov/sigma2;
end